// src/main/java/sn/edu/tju/elm/repository/WalletTransactionRepository.java
package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.model.WalletTransaction;
import cn.edu.tju.elm.model.TransactionType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;  // 添加这个import
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;    // 添加这个import

@Repository
public interface WalletTransactionRepository extends JpaRepository<WalletTransaction, Long> {
    
    /**
     * 根据钱包ID查找交易流水
     */
    List<WalletTransaction> findByWalletIdOrderByCreateTimeDesc(Long walletId);
    
    /**
     * 根据钱包ID和交易类型查找
     */
    List<WalletTransaction> findByWalletIdAndTransactionTypeOrderByCreateTimeDesc(
        Long walletId, TransactionType transactionType);
    
    /**
     * 根据时间范围查找交易流水
     */
    List<WalletTransaction> findByWalletIdAndCreateTimeBetweenOrderByCreateTimeDesc(
        Long walletId, LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 根据参考ID查找交易（如订单号）
     */
    Optional<WalletTransaction> findByReferenceId(String referenceId);
    
    /**
     * 统计钱包的总收入
     */
    @Query("SELECT COALESCE(SUM(t.amount), 0) FROM WalletTransaction t WHERE t.walletId = :walletId AND t.amount > 0")
    BigDecimal getTotalIncome(@Param("walletId") Long walletId);
    
    /**
     * 统计钱包的总支出
     */
    @Query("SELECT COALESCE(SUM(t.amount), 0) FROM WalletTransaction t WHERE t.walletId = :walletId AND t.amount < 0")
    BigDecimal getTotalExpense(@Param("walletId") Long walletId);
}